package com.blvtphan.tipocketclubs.gui;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.blvtphan.tipocketclubs.R;
import com.blvtphan.tipocketclubs.abstracts.AbstractActivity;
import com.blvtphan.tipocketclubs.adapter.RewardTrackerAdapter;
import com.blvtphan.tipocketclubs.api.ApiConstant;
import com.blvtphan.tipocketclubs.api.ApiHelper;
import com.blvtphan.tipocketclubs.custom.CustomButton;
import com.blvtphan.tipocketclubs.custom.CustomEditText;
import com.blvtphan.tipocketclubs.custom.CustomTextView;
import com.blvtphan.tipocketclubs.model.RewardsModel;
import com.blvtphan.tipocketclubs.system.UserSetting;
import com.blvtphan.tipocketclubs.util.ConnectionUtils;
import com.blvtphan.tipocketclubs.util.Constants;
import com.blvtphan.tipocketclubs.util.GeneralUtils;
import com.blvtphan.tipocketclubs.util.PreferenceUtils;
import com.blvtphan.tipocketclubs.widget.CustomAlertDialog;

public class VerifyTrackActivity extends AbstractActivity{
	
	private CustomTextView mTvWelcome;
	private CustomTextView mTvCompany;
	private CustomTextView mTvFullname;
	private CustomTextView mTvDate;
	private CustomEditText mEdtAmountPre;
	private CustomEditText mEdtAmountSaved;
	private CustomEditText mEdtAmountTotal;
	private CustomButton mBtnSubmit;
	private ImageView mBtnPullRewards;
	private List<RewardsModel> lstRewards;
	private boolean isPullOffer = false;
	
	// data 
	private String merchantName, merchantId;
	private int rewardPos=0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		savedInstanceState = getIntent().getExtras();
		initData(savedInstanceState);
	}
	
	@SuppressWarnings("unchecked")
	private void initData(Bundle bundle) {
		if (bundle != null) {
			merchantName = bundle.getString(Constants.CheckMerchantCodeExtras.MERCHANT_NAME);
			merchantId = bundle.getString(Constants.CheckMerchantCodeExtras.MERCHANT_ID);
			
			mTvWelcome.setText(getResources().getString(R.string.text_welcome_to_merchant).replace("{0}", merchantName));
			try {
				lstRewards = (List<RewardsModel>) GeneralUtils
						.bytes2Object(getIntent().getByteArrayExtra(
								Constants.CheckMerchantCodeExtras.LIST_REWARDS));
				Log.i("VERIFY", lstRewards.size()+"");
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
		
		mTvCompany.setText(UserSetting.getInstance().getCompany());
		mTvFullname.setText(UserSetting.getInstance().getUserFullName());
		mTvDate.setText("31/03/2013");
	}
	
	private void checkAndSubmitTransaction() {
		if(!mEdtAmountPre.getText().toString().equals("") && !mEdtAmountSaved.getText().toString().equals("")) {
			submitTracker(merchantId, mEdtAmountPre.getText().toString(), mEdtAmountSaved.getText().toString(),
					lstRewards.get(rewardPos).getId());
		} else {
			GeneralUtils.showToastMessage(mContext, getResources().getString(R.string.mess_fill_all_fields), Toast.LENGTH_SHORT);
		}
	}
	
	private void showDialogRewardsList() {
		View enterView = LayoutInflater.from(mContext).inflate(R.layout.list_rewards_submit_transaction, null, true);
		final CustomAlertDialog dialog = new CustomAlertDialog(mContext, enterView);
		dialog.setButton(getResources().getString(R.string.cancel_button), new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				dialog.hideDialog();
			}
		});
		ListView lstView = (ListView)enterView.findViewById(R.id.list_rewards_transaction);
//		lstRewards.add(lstRewards.get(0));
		lstView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapter, View view, int pos, long id) {
				dialog.hideDialog();
				isPullOffer = true;
				rewardPos = pos;
				mEdtAmountSaved.setText(calAndSetTotalAmount(mEdtAmountPre.getText().toString(), lstRewards.get(pos).getDiscount(), true));
			}
		});
		RewardTrackerAdapter adapter = new RewardTrackerAdapter(mContext, lstRewards);
		lstView.setAdapter(adapter);
		
		dialog.setTitle(getResources().getString(R.string.title_select_offer));
		dialog.showDialog();
	}
	
	private String calAndSetTotalAmount(String preAmount, String savedAmount, boolean isPullReward) {
		String resultString = "";
		if(!preAmount.equals("") && !savedAmount.equals("")) {
			float pre = Float.valueOf(preAmount);
			float saved = Float.valueOf(savedAmount);
			DecimalFormat df = new DecimalFormat();
			df.setMaximumFractionDigits(0);
			if(!isPullReward) {
				float total = pre - saved;
				String totalString = String.valueOf(df.format(total));
				mEdtAmountTotal.setText(totalString);
				resultString = saved+"";
			} else {
				saved = pre*saved/100;
				float total = pre - saved;
				String totalString = String.valueOf(df.format(total));
				mEdtAmountTotal.setText(totalString);
				resultString = saved+"";
			}
		} else {
			mEdtAmountTotal.setText("");
		}
		return resultString;
	}
	
	private void submitTracker(String merchantId, String preAmount, String discount, String rewardId) {
		String url = ApiHelper.genAPI(ApiConstant.API.API_POST_SUBMIT_TRACKER);
		url = url.replace("{0}", UserSetting.getInstance().getToken());
		
		Map<String, String> params = new HashMap<String, String>();
		params.put("card_id", "6");
		params.put("merchant_id", merchantId);
		params.put("pre_discount_amount", preAmount);
		params.put("discount_amount", discount);
		if(isPullOffer)
			params.put("reward_id", rewardId);	

		List<NameValuePair> contents = PreferenceUtils
				.createHttpParams(params);
		
		ConnectionUtils.ExcuteHttpPostThread excuteHttpPost = new ConnectionUtils.ExcuteHttpPostThread(
				mContext, mProcessPostSubmitTransaction, url, contents);
		excuteHttpPost.execute();
	}
	
	/**
	 * Handler login
	 */
	private Handler mProcessPostSubmitTransaction = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Constants.APIConstant.HANDLER_REQUEST_FAIL:
				// Connect fail
				GeneralUtils.showAlertDialog(mContext,
						mContext.getString(R.string.error_title),
						mContext.getString(R.string.msg_connect_servier_fail));
				break;
			case Constants.APIConstant.HANDLER_REQUEST_SUCCESS:
				String result = (String) msg.obj;
				Log.i("QRCode", result);
				try {
					JSONObject obj = new JSONObject(result);
					if (!obj.isNull(ApiConstant.JsonType.DATA)) {
						// Set userId
						
					} else {
						
					}
				} catch (JSONException e) {
					e.printStackTrace();
					// Wrong
					GeneralUtils.showAlertDialog(mContext,
							mContext.getString(R.string.error_title),
							mContext.getString(R.string.msg_connect_servier_fail));
				}
				break;
			default:
				break;
			}
		}
	};

	@Override
	public int getContentViewId() {
		return R.layout.activity_verify_track;
	}

	@Override
	public void initView() {

		mTvWelcome = (CustomTextView)findViewById(R.id.txt_verify_welcome_merchant);
		mTvCompany = (CustomTextView)findViewById(R.id.txt_verify_company);
		mTvFullname = (CustomTextView)findViewById(R.id.txt_verify_fullname);
		mTvDate = (CustomTextView)findViewById(R.id.txt_verify_date);
		mEdtAmountPre = (CustomEditText)findViewById(R.id.edt_verify_amount_pre);
		mEdtAmountSaved = (CustomEditText)findViewById(R.id.edt_verify_amount_saved);
		mEdtAmountTotal = (CustomEditText)findViewById(R.id.edt_verify_amount_total);
		mBtnSubmit = (CustomButton)findViewById(R.id.btn_submit_tracker);
		mBtnPullRewards = (ImageView)findViewById(R.id.btn_verify_choose_offer);
		mBtnPullRewards.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showDialogRewardsList();
			}
		});
		mEdtAmountPre.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				calAndSetTotalAmount(s.toString(), mEdtAmountSaved.getText().toString(), false);
			}
		});
		mEdtAmountSaved.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				isPullOffer = false;
				calAndSetTotalAmount(mEdtAmountPre.getText().toString(), s.toString(), false);
			}
		});
		mBtnSubmit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				checkAndSubmitTransaction();
			}
		});
	}

	@Override
	public String getTitleBarTitle() {
		return mContext.getString(R.string.title_my_card);
	}
	
}
